# encoding=utf-8

from VarDefine import *
from openpyxl import load_workbook


def convert_str(input_str):
    if input_str == BLANK_STR:
        return BLANK
    elif input_str == PIC_UNREADABLE_STR:
        return PIC_UNREADABLE
    elif input_str == DR_UN_SEEN_STR:
        return DR_UN_SEEN
    elif input_str == DR_CON_STR:
        return DR_CON
    elif input_str == DR_LOW_UN_CON_STR:
        return DR_LOW_UN_CON
    elif input_str == DR_MIDDLE_UN_CON_STR:
        return DR_MIDDLE_UN_CON
    elif input_str == DR_HIGH_UN_CON_STR:
        return DR_HIGH_UN_CON

    return None


def build_row_dict(each_row: dict):
    d = {
        "name": each_row[PATIENT_NAME].value,
        "sex": each_row[PATIENT_SEX].value,
        "age": each_row[PATIENT_AGE].value,
        "left": convert_str(each_row[PATIENT_EYE_LEFT].value),
        "right": convert_str(each_row[PATIENT_EYE_RIGHT].value),
        "check_data": each_row[PATIENT_CHECK_DATA].value
    }

    assert d["name"] is not None or d["name"] != ""
    assert d["left"] is not None or d["left"] != ""
    assert d["right"] is not None or d["right"] != ""

    return d


def load_book(filename: str, limit: int = -1):
    wb = load_workbook(filename, data_only=True)
    sheet = wb[EXCEL_SHEET_NAME]

    data_dict = {}
    i = 0
    for row in sheet.iter_rows(min_row=EXCEL_DATA_START):
        p_id = row[PATIENT_NUMBER].value
        p_dict = build_row_dict(row)
        data_dict[p_id] = p_dict

        if limit != -1:
            i += 1
            if i > limit:
                break

    wb.close()
    return data_dict


if __name__ == '__main__':
    d = load_book("糖网筛查_20240403 090453.xlsx")
    print(d)
